// pages/nearbyStores/nearbyStores.js
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var QQMapWX = require('../../map/qqmap-wx-jssdk.js');
var qqmapsdk;
var lati = null
var longi = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loadingHidden:false,
    isMore:true,
    isActive:-1,
    active: 0,
    limit:4,
    page:1,
    totalPage:'',
    /** 页面配置 */
    winWidth: 0,
    winHeight: 0,
    // tab切换  
    currentTab: 0,
    storeMenu: [],
    storeList:[],
    storeType:-1,
    filtrateList:[
      { name: '积分优先', value: 1 }, { name: '口碑优先', value: 2 }, { name: '等级优先', value: 3 }, { name: '距离最近', value: 4 }
    ],
  },

  onChange(event) {
    var title = event.detail.title
    var storeMenu = this.data.storeMenu
    var active;
    storeMenu.forEach(e=>{
      if(e.name === title){
        active = e.code
      }
    })
    this.setData({
      active: event.detail.index,
      storeType: active,
      storeList:[],
      page:1,
      isMore:false
    })
    this.getStoreList()
  },

  compare(property){
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      return value1 - value2;
    }
  },

  map(arr){
    arr.forEach(e => {
      // 获取当前的地理位置
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          lati = res.latitude
          longi = res.longitude
          // console.log('我的经纬度', lati, longi)
        }
      })
      // 实例化API核心类
      var qqMap = new QQMapWX({
        key: 'NTGBZ-BFCPS-2V3OV-6VPL6-URPC3-FZFEX',//'申请的key'
      });
      qqMap.geocoder({
        address: e.storeAddress,   //用户输入的地址（注：地址中请包含城市名称，否则会影响解析效果），如：'北京市海淀区彩和坊路海淀西大街74号'
        complete: res => {
          if (res.status == 0) {
            // console.log('商家经纬度', res.result.location);   //经纬度对象
            // 计算两地距离
            e.distance = util.getDistance(lati, longi, res.result.location.lat, res.result.location.lng)
          } else {
            util.alert(e.storeAddress + '地址无法解析')
            e.distance = 0
          }
        }
      });
    })
  },
  


  //过滤
  filtrate(e){
    let item = e.currentTarget.dataset.item
    if(item.value == 4){
      this.setData({
        storeList: this.data.storeList.sort(this.compare('distance')),
        isActive: e.currentTarget.dataset.index
      })
    }else{
      this.setData({
        storeList: [],
        isActive: e.currentTarget.dataset.index,
        page:1,
        isMore:true
      })
      let data = { limit: this.data.limit, page: this.data.page, sort: item.value, type: this.data.storeType }
      util.request(api.filtrate, data).then((res) => {
        if (res.errno == 0) {
          this.map(res.data.list)
          setTimeout(() => {
            var storeListTem = this.data.storeList
            if (this.data.page == 1) {
              storeListTem = []
            }
            var storeList = res.data.list
            if (storeList.length < this.data.limit) {
              this.setData({
                storeList: storeListTem.concat(storeList),
                isMore: false,
              })
            } else {
              this.setData({
                storeList: storeListTem.concat(storeList),
                isMore: true,
                page: this.data.page + 1,
              })
            }
          }, 500)
          this.setData({ loadingHidden: true })

        }
      })
    }
  },





// 获取店铺列表
  getStoreList(){
    let data = {limit:this.data.limit,page:this.data.page,type:this.data.storeType}
    var storeListTem = this.data.storeList
    util.request(api.storeList,data).then((res)=>{
      if (res.errno == 0){
        this.map(res.data.list)
        setTimeout(()=>{
          if(this.data.page == 1){
            storeListTem = []
          }
          var storeList = res.data.list
          if(storeList.length< this.data.limit){
            this.setData({
              storeList : storeListTem.concat(storeList),
              isMore:false,
            })
          }else{
            this.setData({
              storeList: storeListTem.concat(storeList),
              isMore: true,
              page:this.data.page + 1,
            })
          }
        },500)
        this.setData({loadingHidden:true})
      }else{
        util.showErrorToast(res.mag)
      }
    })
  },

  getStoreMenu(){
    util.request(api.storeMenu).then((res)=>{
      if(res.errno == 0){
        this.setData({ storeMenu: res.data})
      }else{
        util.showErrorToast(res.msg)
      }
    })
  },
  intoMap(e) {
    var item = e.currentTarget.dataset.item
    var storeAddress
    var location
    var myLatitude
    var myLongitude
    // 实例化API核心类
    var demo = new QQMapWX({
      key: 'NTGBZ-BFCPS-2V3OV-6VPL6-URPC3-FZFEX',//'申请的key'
    });
    demo.geocoder({
      address: item.storeAddress,   //用户输入的地址（注：地址中请包含城市名称，否则会影响解析效果），如：'北京市海淀区彩和坊路海淀西大街74号'
      complete: res => {
        storeAddress = res.result.address_components
        location = res.result.location
      }
    });

    setTimeout(()=>{
      wx.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function (res) {  //因为这里得到的是你当前位置的经纬度
          myLatitude = res.latitude
          myLongitude = res.longitude
          console.log('sadasd', res)
          wx.openLocation({        //所以这里会显示你当前的位置
            latitude: location.lat,
            longitude: location.lng,
            name: storeAddress.province,
            address: item.storeAddress,
            scale: 28
          })
        }
      })
    },300)
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(options.active !== undefined){
      that.setData({ 
        storeType:options.active,
        active:options.active
      })
      this.getStoreList()
    }else{
      this.getStoreList()
    }

    /* 获取系统信息,给页面高度赋值 */
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    // var active = that.data.active
    // that.setData({storeType:active+1})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getStoreMenu()
    // this.getStoreList()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.page = 1
    this.getStoreList()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.isMore){
      this.searchScrollLower()
    }else{
      util.showErrorToast('没有更多数据了')
    }
  },
  searchScrollLower() {
      this.setData({ loadingHidden: false })
      this.getStoreList() 
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})